package nc.tb.ufo.ui;

import java.awt.Container;
import java.util.HashMap;

import nc.tb.pub.cache.NtbCacheManager;
import nc.tb.pub.data.INtbCache;
import nc.tb.report.ViewUIModel;
import nc.ui.pub.ToftPanel;
import nc.ui.pub.beans.UIDialog;

public class ViewUIModelUICache implements INtbCache {
	private final static String CACHE_KEY = "ViewUIModelUICache";
	private HashMap<ViewUIModel, UFOTablePane> hmVmodel2Ufo = new HashMap<ViewUIModel, UFOTablePane>();
	static{
		ViewUIModelUICache inst = (ViewUIModelUICache)NtbCacheManager.getCacheInstance(CACHE_KEY);
		if(inst == null) {
			inst = new ViewUIModelUICache();
			NtbCacheManager.putCacheInstance(CACHE_KEY, inst);
		}
	}
	public void clearCache() {
		hmVmodel2Ufo.clear();
	}
	
	public static ViewUIModelUICache getInstance() {
		ViewUIModelUICache inst = (ViewUIModelUICache)NtbCacheManager.getCacheInstance(CACHE_KEY);
		if(inst == null) {
			inst = new ViewUIModelUICache();
			NtbCacheManager.putCacheInstance(CACHE_KEY, inst);
		}
		return inst;
	}
	
	public boolean checkIsUsed(ViewUIModel model, UFOTablePane ufoTablePane) {
		refresh();
		UFOTablePane ufo = hmVmodel2Ufo.get(model);
		if (ufo == null || ufo == ufoTablePane) {
			hmVmodel2Ufo.put(model, ufoTablePane);
			return false;
		}
		else
			return true;
	}
	
	public void refresh() {
		if(hmVmodel2Ufo.isEmpty())
			return ;
		ViewUIModel[] keys = hmVmodel2Ufo.keySet().toArray(new ViewUIModel[0]);
		if (keys != null) {
			for (int i=0; i<keys.length; i++) {
				UFOTablePane ufo = hmVmodel2Ufo.get(keys[i]);
				if (ufo == null)
					continue;
				if (!hasParent(ufo))
					hmVmodel2Ufo.remove(keys[i]);
			}
		}
	}

	private boolean hasParent(Container ufo) {
		while (ufo != null) {
			if (ufo instanceof ToftPanel || ufo instanceof UIDialog) {
				return true;
			}
			ufo = ufo.getParent();
		}
		return false;
	}
}
